import type { IObject } from '@/types/customs';

/**
 * 验证是否为空
 * @param {any} obj
 * @returns {boolean}
 */
export function isEmpty(obj: unknown) {
  if (obj === null || obj === undefined) { return true; }
  if (
    Object.prototype.toString.call(obj) === '[object Array]'
    && (obj as unknown as IObject[]).length! === 0
  ) {
    return true
  }
  if (typeof obj === 'object') { return Object.keys(obj).length === 0; }
  return false;
}

export function isNotEmpty(obj: unknown) {
  return obj !== '' && obj !== null && !Number.isNaN(obj) && obj !== undefined;
}

/**
 * 获取对象中的值
 * @param {Record<string, any>} origin
 * @param {string} keysUrl
 * @param {any} defaultData
 * @returns {any}
 *
 * example: getValue({a: {b: {c: [1]}}}, 'a.b.c:0') => 1
 */
export function getValue(origin: IObject, keysUrl: string, defaultData: any = []) {
  const keys = keysUrl.split('.');
  let value = origin;
  for (const key of keys) {
    if (key.includes(':')) {
      const [keyName, index] = key.split(':');
      const target = value[keyName] || [];
      value = target[index];
    }
    else {
      value = value[key];
    }

    if (typeof value === 'undefined' || value === null) {
      value = {};
    }
  }
  return isEmpty(value) ? defaultData : value;
}

export function getUchatsUid() {
  return `chart-${Math.random().toString(36).substring(2, 15)}${Date.now()}`;
}
